import axios from 'axios';
import {
  showFullScreenLoading,
  tryHideFullScreenLoading,
} from '@/utils/Loading';

import { ElMessage } from 'element-plus';

const request = axios.create({
  baseUrl: '/',
  timeout: 30000,
});

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    showFullScreenLoading();
    // 在发送请求之前做些什么
    if (window.sessionStorage.uid) {
      const uid = window.sessionStorage.uid;
      config.params = {
        ...config.params,
        uid,
      };
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    let code = response.data.code;
    tryHideFullScreenLoading();
    if (code !== 0) {
      ElMessage({
        message: response.data.msg,
        grouping: true,
        center: true,
        showClose: true,
        type: 'error',
      });
      if (code == 401) {
        window.sessionStorage.removeItem('uid');
        location.href = '/login';
      } else {
        return Promise.reject(response.data);
      }
    } else {
      return response.data;
    }
  },
  (error) => {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    tryHideFullScreenLoading();
    return Promise.reject(error);
  }
);

export default request;
